<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>离线语言播放系统演示</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .audio-player { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .progress-bar { transition: width 0.3s ease; }
        .fade-in { animation: fadeIn 0.3s ease-in; }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .hover-scale { transition: transform 0.2s; }
        .hover-scale:hover { transform: scale(1.02); }
    </style>
</head>
<body class="bg-gray-50">
    <!-- 头部导航 -->
    <header class="bg-white shadow-md">
        <div class="container mx-auto px-4 py-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <i class="fas fa-podcast text-purple-600 text-2xl"></i>
                    <h1 class="text-2xl font-bold text-gray-800">离线语言播放系统</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="status-indicator" class="px-3 py-1 rounded-full text-sm bg-gray-200 text-gray-600">
                        <i class="fas fa-circle text-gray-400 mr-2"></i>未连接
                    </button>
                    <button id="settings-btn" class="text-gray-600 hover:text-gray-800">
                        <i class="fas fa-cog"></i>
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 主容器 -->
    <main class="container mx-auto px-4 py-8">
        <!-- 连接状态提示 -->
        <div id="connection-alert" class="mb-6 bg-yellow-50 border border-yellow-200 rounded-md p-4">
            <div class="flex items-center">
                <i class="fas fa-exclamation-triangle text-yellow-600 mr-2"></i>
                <span class="text-yellow-800">正在连接到后端服务...</span>
            </div>
        </div>

        <!-- 标签页导航 -->
        <div class="bg-white rounded-lg shadow-md mb-6">
            <div class="border-b border-gray-200">
                <nav class="flex -mb-px">
                    <button class="tab-btn py-4 px-6 text-sm font-medium text-purple-600 border-b-2 border-purple-600" data-tab="tts">
                        <i class="fas fa-microphone-alt mr-2"></i>语音合成
                    </button>
                    <button class="tab-btn py-4 px-6 text-sm font-medium text-gray-600 hover:text-gray-800" data-tab="audiobook">
                        <i class="fas fa-book mr-2"></i>有声读物
                    </button>
                    <button class="tab-btn py-4 px-6 text-sm font-medium text-gray-600 hover:text-gray-800" data-tab="player">
                        <i class="fas fa-play-circle mr-2"></i>播放器
                    </button>
                    <button class="tab-btn py-4 px-6 text-sm font-medium text-gray-600 hover:text-gray-800" data-tab="voices">
                        <i class="fas fa-user-voice mr-2"></i>语音库
                    </button>
                </nav>
            </div>
        </div>

        <!-- 标签页内容 -->
        <div class="tab-content active" id="tts">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <!-- TTS输入面板 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-xl font-bold mb-4">
                        <i class="fas fa-keyboard mr-2 text-purple-600"></i>文本输入
                    </h2>
                    
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">输入文本</label>
                        <textarea id="tts-text" class="w-full p-3 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" rows="6" placeholder="请输入要合成语音的文本...">你好，欢迎使用离线语言播放系统。这是一个功能强大的语音合成和有声读物制作工具。</textarea>
                        <div class="mt-2 text-right">
                            <span id="text-count" class="text-sm text-gray-500">33 / 5000 字符</span>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4 mb-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">选择语音</label>
                            <select id="voice-select" class="w-full p-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500">
                                <option value="">加载中...</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">输出格式</label>
                            <select id="format-select" class="w-full p-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500">
                                <option value="mp3">MP3</option>
                                <option value="wav">WAV</option>
                                <option value="ogg">OGG</option>
                            </select>
                        </div>
                    </div>

                    <!-- 语音设置滑块 -->
                    <div class="space-y-4 mb-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                语速: <span id="rate-value">1.0</span>
                            </label>
                            <input type="range" id="rate-slider" min="0.5" max="2.0" step="0.1" value="1.0" class="w-full">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                音量: <span id="volume-value">1.0</span>
                            </label>
                            <input type="range" id="volume-slider" min="0.0" max="1.0" step="0.1" value="1.0" class="w-full">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                音调: <span id="pitch-value">1.0</span>
                            </label>
                            <input type="range" id="pitch-slider" min="0.5" max="2.0" step="0.1" value="1.0" class="w-full">
                        </div>
                    </div>

                    <button id="tts-synthesize" class="w-full bg-purple-600 text-white py-3 px-4 rounded-md hover:bg-purple-700 transition duration-200 flex items-center justify-center">
                        <i class="fas fa-magic mr-2"></i>
                        <span>合成语音</span>
                    </button>
                </div>

                <!-- TTS结果面板 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-xl font-bold mb-4">
                        <i class="fas fa-file-audio mr-2 text-purple-600"></i>语音结果
                    </h2>
                    
                    <div id="tts-loading" class="hidden">
                        <div class="flex items-center justify-center py-8">
                            <div class="loading-spinner mr-3"></div>
                            <span class="text-gray-600">正在合成语音...</span>
                        </div>
                    </div>

                    <div id="tts-result" class="hidden fade-in">
                        <div class="mb-4 p-4 bg-green-50 border border-green-200 rounded-md">
                            <div class="flex items-center">
                                <i class="fas fa-check-circle text-green-500 mr-2"></i>
                                <span class="text-green-800">语音合成成功！</span>
                            </div>
                        </div>

                        <div id="audio-info" class="mb-4 space-y-2">
                            <!-- 音频信息将在这里显示 -->
                        </div>

                        <div id="audio-player-container" class="mb-4">
                            <!-- 音频播放器将在这里插入 -->
                        </div>

                        <div class="flex space-x-4">
                            <button id="download-audio" class="flex-1 bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 transition duration-200">
                                <i class="fas fa-download mr-2"></i>下载音频
                            </button>
                            <button id="copy-url" class="flex-1 bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition duration-200">
                                <i class="fas fa-copy mr-2"></i>复制链接
                            </button>
                        </div>
                    </div>

                    <div id="tts-error" class="hidden fade-in">
                        <div class="p-4 bg-red-50 border border-red-200 rounded-md">
                            <div class="flex items-center">
                                <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                                <span class="text-red-800" id="tts-error-message">语音合成失败</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 有声读物标签页 -->
        <div class="tab-content" id="audiobook">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- 创建有声读物 -->
                <div class="lg:col-span-1 bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-xl font-bold mb-4">
                        <i class="fas fa-plus-circle mr-2 text-purple-600"></i>创建有声读物
                    </h2>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">标题</label>
                            <input type="text" id="audiobook-title" class="w-full p-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" placeholder="输入标题..." value="示例有声读物">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">作者</label>
                            <input type="text" id="audiobook-author" class="w-full p-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" placeholder="输入作者..." value="系统演示">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">内容</label>
                            <textarea id="audiobook-content" class="w-full p-3 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" rows="8" placeholder="输入有声读物内容...">这是第一章节的内容。在这个章节中，我们将介绍离线语言播放系统的基本功能和使用方法。首先，让我们了解一下如何进行文本到语音的转换。

这是第二章节的内容。在本章节中，我们将深入探讨有声读物的制作流程，包括内容分割、语音选择和音频合成等技术细节。通过掌握这些知识，您将能够制作出高质量的有声读物。</textarea>
                        </div>
                        
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="auto-chapters" class="mr-2" checked>
                                <span class="text-sm font-medium text-gray-700">自动分章节</span>
                            </label>
                        </div>
                        
                        <button id="create-audiobook" class="w-full bg-purple-600 text-white py-3 px-4 rounded-md hover:bg-purple-700 transition duration-200">
                            <i class="fas fa-book-open mr-2"></i>创建有声读物
                        </button>
                    </div>
                </div>

                <!-- 有声读物列表 -->
                <div class="lg:col-span-2 bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-xl font-bold mb-4">
                        <i class="fas fa-list mr-2 text-purple-600"></i>我的有声读物
                    </h2>
                    
                    <div id="audiobook-loading" class="hidden">
                        <div class="flex items-center justify-center py-8">
                            <div class="loading-spinner mr-3"></div>
                            <span class="text-gray-600">加载中...</span>
                        </div>
                    </div>

                    <div id="audiobook-list" class="space-y-4">
                        <!-- 有声读物列表将在这里显示 -->
                    </div>

                    <div id="audiobook-empty" class="text-center py-8 text-gray-500">
                        <i class="fas fa-book-reader text-4xl mb-4 text-gray-300"></i>
                        <p>还没有有声读物</p>
                        <p class="text-sm">创建您的第一个有声读物吧！</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 播放器标签页 -->
        <div class="tab-content" id="player">
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-bold mb-4">
                    <i class="fas fa-play-circle mr-2 text-purple-600"></i>音频播放器
                </h2>
                
                <div id="player-empty" class="text-center py-12 text-gray-500">
                    <i class="fas fa-headphones text-4xl mb-4 text-gray-300"></i>
                    <p>选择一个有声读物开始播放</p>
                    <p class="text-sm">前往"有声读物"标签页</p>
                </div>

                <div id="player-content" class="hidden">
                    <!-- 播放器信息 -->
                    <div class="mb-6">
                        <h3 id="player-title" class="text-lg font-bold mb-2">有声读物标题</h3>
                        <p id="player-author" class="text-gray-600 mb-1">作者</p>
                        <div class="flex items-center space-x-4 text-sm text-gray-500">
                            <span id="player-duration">时长: 0:00</span>
                            <span id="player-status">状态: 就绪</span>
                        </div>
                    </div>

                    <!-- 音频播放器 -->
                    <div class="audio-player rounded-lg p-6 mb-6">
                        <div class="bg-white bg-opacity-90 rounded-lg p-4">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">播放进度</label>
                                <div class="relative">
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div id="progress-bar" class="bg-green-500 h-2 rounded-full progress-bar" style="width: 0%"></div>
                                    </div>
                                    <div class="flex justify-between mt-1 text-xs text-gray-600">
                                        <span id="current-time">0:00</span>
                                        <span id="total-time">0:00</span>
                                    </div>
                                </div>
                            </div>

                            <!-- 播放控制按钮 -->
                            <div class="flex items-center justify-center space-x-4 mb-4">
                                <button id="btn-prev" class="bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-3 transition duration-200">
                                    <i class="fas fa-step-backward text-gray-700"></i>
                                </button>
                                <button id="btn-play-pause" class="bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-4 transition duration-200">
                                    <i class="fas fa-play text-gray-700 text-xl"></i>
                                </button>
                                <button id="btn-next" class="bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-3 transition duration-200">
                                    <i class="fas fa-step-forward text-gray-700"></i>
                                </button>
                            </div>

                            <!-- 音量控制 -->
                            <div class="flex items-center justify-center space-x-4">
                                <i class="fas fa-volume-down text-gray-600"></i>
                                <input type="range" id="volume-control" min="0" max="100" value="70" class="w-32">
                                <i class="fas fa-volume-up text-gray-600"></i>
                                <span id="volume-display" class="text-sm text-gray-600">70%</span>
                            </div>
                        </div>
                    </div>

                    <!-- 章节列表 -->
                    <div>
                        <h4 class="text-lg font-bold mb-3">章节列表</h4>
                        <div id="chapter-list" class="space-y-2">
                            <!-- 章节列表将在这里显示 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 语音库标签页 -->
        <div class="tab-content" id="voices">
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-bold mb-4">
                    <i class="fas fa-user-voice mr-2 text-purple-600"></i>语音库
                </h2>
                
                <div class="mb-6">
                    <div class="flex items-center space-x-4 mb-4">
                        <div class="flex-1">
                            <input type="text" id="voice-search" class="w-full p-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" placeholder="搜索语音...">
                        </div>
                        <select id="voice-filter" class="p-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500">
                            <option value="">所有语言</option>
                            <option value="zh-CN">中文</option>
                            <option value="en-US">英文</option>
                            <option value="ja-JP">日文</option>
                        </select>
                        <select id="gender-filter" class="p-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500">
                            <option value="">所有性别</option>
                            <option value="male">男声</option>
                            <option value="female">女声</option>
                        </select>
                    </div>
                </div>

                <div id="voices-loading" class="hidden">
                    <div class="flex items-center justify-center py-8">
                        <div class="loading-spinner mr-3"></div>
                        <span class="text-gray-600">加载语音库...</span>
                    </div>
                </div>

                <div id="voices-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <!-- 语音卡片将在这里显示 -->
                </div>
            </div>
        </div>
    </main>

    <!-- 设置模态框 -->
    <div id="settings-modal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-medium text-gray-900 mb-4">设置</h3>
                
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">API基础URL</label>
                        <input type="text" id="api-base-url" class="w-full p-2 border border-gray-300 rounded-md" value="http://localhost:8000">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">访问令牌</label>
                        <input type="password" id="api-token" class="w-full p-2 border border-gray-300 rounded-md" placeholder="输入您的访问令牌">
                    </div>
                    
                    <div>
                        <label class="flex items-center">
                            <input type="checkbox" id="auto-play" class="mr-2">
                            <span class="text-sm font-medium text-gray-700">自动播放</span>
                        </label>
                    </div>
                    
                    <div>
                        <label class="flex items-center">
                            <input type="checkbox" id="show-notifications" class="mr-2" checked>
                            <span class="text-sm font-medium text-gray-700">显示通知</span>
                        </label>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-4 mt-6">
                    <button id="settings-cancel" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">
                        取消
                    </button>
                    <button id="settings-save" class="px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700">
                        保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知容器 -->
    <div id="notification-container" class="fixed top-4 right-4 z-50 space-y-2">
        <!-- 通知将在这里显示 -->
    </div>

    <!-- 应用脚本 -->
    <script>
        // 应用状态管理
        const AppState = {
            isConnected: false,
            baseUrl: 'http://localhost:8000',
            token: '',
            currentAudiobook: null,
            currentAudio: null,
            voices: [],
            settings: {
                autoPlay: localStorage.getItem('auto-play') === 'true',
                showNotifications: localStorage.getItem('show-notifications') !== 'false'
            }
        };

        // 模拟语音数据
        const mockVoices = [
            { id: '0', name: '小雅 (中文女声)', language: 'zh-CN', gender: 'female', engine: 'pyttsx3' },
            { id: '1', name: '小明 (中文男声)', language: 'zh-CN', gender: 'male', engine: 'pyttsx3' },
            { id: '2', name: 'Sarah (英语女声)', language: 'en-US', gender: 'female', engine: 'pyttsx3' },
            { id: '3', name: 'John (英语男声)', language: 'en-US', gender: 'male', engine: 'pyttsx3' },
            { id: '4', name: 'さくら (日语女声)', language: 'ja-JP', gender: 'female', engine: 'pyttsx3' },
            { id: '5', name: 'けんじ (日语男声)', language: 'ja-JP', gender: 'male', engine: 'pyttsx3' }
        ];

        // 初始化应用
        async function initApp() {
            try {
                // 检查连接状态
                await checkConnection();
                
                // 加载语音库
                await loadVoices();
                
                // 绑定事件监听器
                bindEventListeners();
                
                console.log('应用初始化完成');
            } catch (error) {
                console.error('应用初始化失败:', error);
                showNotification('应用初始化失败: ' + error.message, 'error');
            }
        }

        // 检查连接状态
        async function checkConnection() {
            try {
                const response = await fetch(`${AppState.baseUrl}/health/`);
                const data = await response.json();
                
                if (data.status === 'healthy' || data.status === 'ok') {
                    AppState.isConnected = true;
                    updateConnectionStatus('connected');
                    hideElement('connection-alert');
                    
                    // 加载真实数据
                    await loadVoices();
                    await loadAudiobooks();
                } else {
                    throw new Error('服务不可用');
                }
            } catch (error) {
                AppState.isConnected = false;
                updateConnectionStatus('disconnected');
                showConnectionError();
                
                // 每5秒重新检查连接
                setTimeout(checkConnection, 5000);
            }
        }

        // 更新连接状态
        function updateConnectionStatus(status) {
            const indicator = document.getElementById('status-indicator');
            
            if (status === 'connected') {
                indicator.className = 'px-3 py-1 rounded-full text-sm bg-green-100 text-green-800';
                indicator.innerHTML = '<i class="fas fa-circle text-green-500 mr-2"></i>已连接';
            } else {
                indicator.className = 'px-3 py-1 rounded-full text-sm bg-red-100 text-red-800';
                indicator.innerHTML = '<i class="fas fa-circle text-red-500 mr-2"></i>未连接';
            }
        }

        // 显示连接错误
        function showConnectionError() {
            const alert = document.getElementById('connection-alert');
            alert.className = 'mb-6 bg-red-50 border border-red-200 rounded-md p-4';
            alert.innerHTML = `
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle text-red-600 mr-2"></i>
                        <span class="text-red-800">无法连接到后端服务 (${AppState.baseUrl})</span>
                    </div>
                    <button onclick="checkConnection()" class="text-red-600 hover:text-red-800">
                        <i class="fas fa-redo"></i> 重试
                    </button>
                </div>
            `;
        }

        // 绑定事件监听器
        function bindEventListeners() {
            // 标签页切换
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const tabName = btn.dataset.tab;
                    switchTab(tabName);
                });
            });

            // TTS功能
            document.getElementById('tts-synthesize').addEventListener('click', synthesizeSpeech);
            document.getElementById('tts-text').addEventListener('input', updateTextCount);
            
            // 语音设置滑块
            ['rate', 'volume', 'pitch'].forEach(param => {
                const slider = document.getElementById(`${param}-slider`);
                const value = document.getElementById(`${param}-value`);
                slider.addEventListener('input', () => {
                    value.textContent = slider.value;
                });
            });

            // 有声读物功能
            document.getElementById('create-audiobook').addEventListener('click', createAudiobook);

            // 播放器控制
            document.getElementById('btn-play-pause').addEventListener('click', togglePlayPause);
            document.getElementById('btn-prev').addEventListener('click', playPrevious);
            document.getElementById('btn-next').addEventListener('click', playNext);
            document.getElementById('volume-control').addEventListener('input', updateVolume);

            // 语音库搜索和过滤
            document.getElementById('voice-search').addEventListener('input', filterVoices);
            document.getElementById('voice-filter').addEventListener('change', filterVoices);
            document.getElementById('gender-filter').addEventListener('change', filterVoices);

            // 设置相关
            document.getElementById('settings-btn').addEventListener('click', showSettings);
            document.getElementById('settings-cancel').addEventListener('click', hideSettings);
            document.getElementById('settings-save').addEventListener('click', saveSettings);
        }

        // 标签页切换
        function switchTab(tabName) {
            // 更新标签按钮状态
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('text-purple-600', 'border-b-2', 'border-purple-600');
                btn.classList.add('text-gray-600');
            });
            
            const activeBtn = document.querySelector(`[data-tab="${tabName}"]`);
            activeBtn.classList.remove('text-gray-600');
            activeBtn.classList.add('text-purple-600', 'border-b-2', 'border-purple-600');

            // 更新标签内容显示
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.getElementById(tabName).classList.add('active');
        }

        // TTS功能
        async function synthesizeSpeech() {
            if (!AppState.isConnected) {
                showNotification('请先连接到后端服务', 'warning');
                return;
            }

            const text = document.getElementById('tts-text').value.trim();
            if (!text) {
                showNotification('请输入要合成的文本', 'warning');
                return;
            }

            const voiceId = document.getElementById('voice-select').value;
            if (!voiceId) {
                showNotification('请选择语音', 'warning');
                return;
            }

            const format = document.getElementById('format-select').value;
            const rate = parseFloat(document.getElementById('rate-slider').value);
            const volume = parseFloat(document.getElementById('volume-slider').value);
            const pitch = parseFloat(document.getElementById('pitch-slider').value);

            try {
                showLoading('tts-loading');
                hideElement('tts-result');
                hideElement('tts-error');

                console.log('准备发送TTS请求，参数：', {
                    text: text.substring(0, 20) + '...',
                    voice_id: voiceId,
                    format: format,
                    rate: rate * 100,
                    volume: volume,
                    pitch: pitch * 100
                });

                // 添加调试信息
                const apiUrl = `${AppState.baseUrl}/api/v1/tts/synthesize`;
                console.log('请求URL:', apiUrl);

                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        text: text,
                        voice_id: voiceId,
                        format: format,
                        rate: rate * 100, // 转换为TTS期望的格式
                        volume: volume,
                        pitch: pitch * 100
                    })
                });

                console.log('收到响应:', response.status, response.statusText);
                const result = await response.json();
                console.log('响应数据:', result);

                if (response.ok && result.success) {
                    hideLoading('tts-loading'); // 先隐藏加载状态
                    showTTSResult(result);
                    showNotification('语音合成成功！', 'success');
                } else {
                    hideLoading('tts-loading'); // 先隐藏加载状态
                    const errorMsg = result.message || result.detail || '语音合成失败';
                    console.error('API返回错误:', errorMsg);
                    showTTSError(errorMsg);
                }
            } catch (error) {
                console.error('语音合成失败:', error);
                hideLoading('tts-loading');
                showTTSError(error.message || '网络错误，请检查连接');
            }
        }

        function showTTSResult(result) {
            const audioInfo = document.getElementById('audio-info');
            audioInfo.innerHTML = `
                <div class="text-sm"><strong>时长:</strong> ${result.duration ? result.duration.toFixed(2) + '秒' : '未知'}</div>
                <div class="text-sm"><strong>格式:</strong> ${result.format?.toUpperCase() || 'MP3'}</div>
                <div class="text-sm"><strong>文件:</strong> ${result.audio_url ? '已生成' : '生成中'}</div>
            `;

            const playerContainer = document.getElementById('audio-player-container');
            
            if (result.audio_url) {
                playerContainer.innerHTML = `
                    <audio controls class="w-full" id="tts-audio">
                        <source src="${AppState.baseUrl}${result.audio_url}" type="audio/${result.format || 'mp3'}">
                        您的浏览器不支持音频播放。
                    </audio>
                `;

                document.getElementById('download-audio').onclick = () => {
                    window.open(`${AppState.baseUrl}${result.audio_url}`, '_blank');
                };

                document.getElementById('copy-url').onclick = () => {
                    copyToClipboard(`${AppState.baseUrl}${result.audio_url}`);
                    showNotification('链接已复制到剪贴板', 'success');
                };
            } else {
                playerContainer.innerHTML = `
                    <div class="p-4 bg-yellow-50 border border-yellow-200 rounded-md">
                        <div class="flex items-center">
                            <i class="fas fa-clock text-yellow-500 mr-2"></i>
                            <span class="text-yellow-800">音频正在后台生成中，请稍候...</span>
                        </div>
                    </div>
                `;
            }

            showElement('tts-result');
        }

        function showTTSError(message) {
            document.getElementById('tts-error-message').textContent = message;
            showElement('tts-error');
        }

        // 有声读物功能
        async function createAudiobook() {
            if (!AppState.isConnected) {
                showNotification('请先连接到后端服务', 'warning');
                return;
            }

            const title = document.getElementById('audiobook-title').value.trim();
            const author = document.getElementById('audiobook-author').value.trim();
            const content = document.getElementById('audiobook-content').value.trim();
            const autoChapters = document.getElementById('auto-chapters').checked;

            if (!title || !content) {
                showNotification('请填写标题和内容', 'warning');
                return;
            }

            try {
                const response = await fetch(`${AppState.baseUrl}/api/v1/audiobooks/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        title: title,
                        author: author,
                        content: content,
                        language: 'zh-CN',
                        auto_chapters: autoChapters,
                        output_format: 'mp3'
                    })
                });

                const result = await response.json();

                if (response.ok) {
                    showNotification('有声读物创建任务已提交', 'success');
                    
                    // 清空表单
                    document.getElementById('audiobook-title').value = '';
                    document.getElementById('audiobook-author').value = '';
                    document.getElementById('audiobook-content').value = '';
                    
                    // 刷新列表
                    await loadAudiobooks();
                } else {
                    showNotification('创建有声读物失败: ' + (result.detail || result.message), 'error');
                }
            } catch (error) {
                console.error('创建有声读物失败:', error);
                showNotification('创建有声读物失败: ' + error.message, 'error');
            }
        }

        async function loadAudiobooks() {
            if (!AppState.isConnected) return;

            try {
                showLoading('audiobook-loading');
                hideElement('audiobook-empty');
                hideElement('audiobook-list');

                const response = await fetch(`${AppState.baseUrl}/api/v1/audiobooks/`);
                const result = await response.json();

                if (response.ok) {
                    if (result.length === 0) {
                        showElement('audiobook-empty');
                    } else {
                        showAudiobookList(result);
                    }
                } else {
                    showElement('audiobook-empty');
                }
            } catch (error) {
                console.error('加载有声读物失败:', error);
                showElement('audiobook-empty');
            } finally {
                hideLoading('audiobook-loading');
            }
        }

        function showAudiobookList(audiobooks) {
            const listContainer = document.getElementById('audiobook-list');
            
            // 模拟一些有声读物数据用于演示
            const mockAudiobooks = [
                {
                    id: 'demo-1',
                    title: '示例有声读物',
                    author: '系统演示',
                    duration: 180,
                    chapters_count: 2,
                    status: 'completed',
                    created_at: new Date().toISOString()
                }
            ];

            const displayBooks = audiobooks.length > 0 ? audiobooks : mockAudiobooks;
            
            listContainer.innerHTML = displayBooks.map(audiobook => `
                <div class="border border-gray-200 rounded-lg p-4 hover-scale cursor-pointer" onclick="selectAudiobook('${audiobook.id}')">
                    <div class="flex justify-between items-start mb-2">
                        <h3 class="font-bold text-lg">${audiobook.title}</h3>
                        <span class="px-2 py-1 text-xs rounded-full ${getStatusClass(audiobook.status || 'completed')}">
                            ${getStatusText(audiobook.status || 'completed')}
                        </span>
                    </div>
                    <p class="text-gray-600 text-sm mb-2">作者: ${audiobook.author || '未知'}</p>
                    <div class="flex items-center text-xs text-gray-500 space-x-4">
                        <span><i class="fas fa-clock mr-1"></i>${formatDuration(audiobook.duration || 0)}</span>
                        <span><i class="fas fa-list-ol mr-1"></i>${audiobook.chapters_count || 2} 章节</span>
                        <span><i class="fas fa-calendar mr-1"></i>${formatDate(audiobook.created_at)}</span>
                    </div>
                </div>
            `).join('');
        }

        // 播放器功能
        async function selectAudiobook(audiobookId) {
            try {
                // 模拟选择有声读物
                const mockAudiobook = {
                    id: audiobookId,
                    title: '示例有声读物',
                    author: '系统演示',
                    duration: 180,
                    chapters: [
                        { id: '1', title: '第一章：系统介绍', duration: 90 },
                        { id: '2', title: '第二章：功能详解', duration: 90 }
                    ]
                };
                
                AppState.currentAudiobook = mockAudiobook;
                showPlayer(mockAudiobook);
                switchTab('player');
                
                showNotification('已选择有声读物: ' + mockAudiobook.title, 'success');
            } catch (error) {
                console.error('加载有声读物失败:', error);
                showNotification('加载有声读物失败: ' + error.message, 'error');
            }
        }

        function showPlayer(audiobook) {
            hideElement('player-empty');
            showElement('player-content');

            document.getElementById('player-title').textContent = audiobook.title;
            document.getElementById('player-author').textContent = `作者: ${audiobook.author || '未知'}`;
            document.getElementById('player-duration').textContent = `时长: ${formatDuration(audiobook.duration)}`;
            document.getElementById('player-status').textContent = '状态: 就绪';
            document.getElementById('total-time').textContent = formatDuration(audiobook.duration);

            // 显示章节列表
            const chapterList = document.getElementById('chapter-list');
            if (audiobook.chapters) {
                chapterList.innerHTML = audiobook.chapters.map(chapter => `
                    <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 cursor-pointer">
                        <div class="flex items-center">
                            <i class="fas fa-play-circle text-purple-600 mr-3"></i>
                            <span class="font-medium">${chapter.title}</span>
                        </div>
                        <span class="text-sm text-gray-500">${formatDuration(chapter.duration)}</span>
                    </div>
                `).join('');
            }
        }

        async function togglePlayPause() {
            // 播放/暂停逻辑
            const btn = document.getElementById('btn-play-pause');
            const icon = btn.querySelector('i');
            
            if (icon.classList.contains('fa-play')) {
                // 开始播放
                icon.classList.remove('fa-play');
                icon.classList.add('fa-pause');
                document.getElementById('player-status').textContent = '状态: 播放中';
                showNotification('开始播放', 'success');
            } else {
                // 暂停播放
                icon.classList.remove('fa-pause');
                icon.classList.add('fa-play');
                document.getElementById('player-status').textContent = '状态: 已暂停';
                showNotification('已暂停', 'info');
            }
        }

        // 语音库功能
        async function loadVoices() {
            try {
                showLoading('voices-loading');
                
                if (AppState.isConnected) {
                    // 尝试从真实API加载语音
                    try {
                        const response = await fetch(`${AppState.baseUrl}/api/v1/tts/voices/`);
                        const result = await response.json();
                        
                        if (response.ok && result.voices) {
                            AppState.voices = result.voices.map(voice => ({
                                id: voice.id,
                                name: voice.name,
                                language: voice.language,
                                gender: voice.gender,
                                engine: voice.engine || 'pyttsx3'
                            }));
                        } else {
                            throw new Error('API响应格式错误');
                        }
                    } catch (apiError) {
                        console.warn('API加载语音失败，使用模拟数据:', apiError);
                        AppState.voices = mockVoices;
                    }
                } else {
                    // 使用模拟数据
                    AppState.voices = mockVoices;
                }
                
                // 填充语音选择器
                populateVoiceSelect();
                showVoicesGrid(AppState.voices);
                
                hideLoading('voices-loading');
            } catch (error) {
                console.error('加载语音库失败:', error);
                // 即使失败也显示模拟数据
                AppState.voices = mockVoices;
                populateVoiceSelect();
                showVoicesGrid(mockVoices);
                hideLoading('voices-loading');
            }
        }

        function populateVoiceSelect() {
            const select = document.getElementById('voice-select');
            select.innerHTML = '<option value="">选择语音</option>' +
                AppState.voices.map(voice => `
                    <option value="${voice.id}">${voice.name} (${voice.language})</option>
                `).join('');
        }

        function showVoicesGrid(voices) {
            const grid = document.getElementById('voices-grid');
            grid.innerHTML = voices.map(voice => `
                <div class="border border-gray-200 rounded-lg p-4 hover-scale cursor-pointer" onclick="testVoice('${voice.id}')">
                    <div class="flex items-center mb-2">
                        <i class="fas fa-user-voice text-purple-600 mr-2"></i>
                        <h3 class="font-bold">${voice.name}</h3>
                    </div>
                    <div class="text-sm text-gray-600 space-y-1">
                        <div><span class="font-medium">语言:</span> ${voice.language}</div>
                        <div><span class="font-medium">性别:</span> ${voice.gender}</div>
                        <div><span class="font-medium">引擎:</span> ${voice.engine}</div>
                    </div>
                    <div class="mt-2">
                        <button class="w-full bg-purple-100 text-purple-700 py-1 px-2 rounded text-sm hover:bg-purple-200">
                            试听
                        </button>
                    </div>
                </div>
            `).join('');
        }

        function filterVoices() {
            const searchTerm = document.getElementById('voice-search').value.toLowerCase();
            const languageFilter = document.getElementById('voice-filter').value;
            const genderFilter = document.getElementById('gender-filter').value;

            const filteredVoices = AppState.voices.filter(voice => {
                const matchesSearch = voice.name.toLowerCase().includes(searchTerm);
                const matchesLanguage = !languageFilter || voice.language === languageFilter;
                const matchesGender = !genderFilter || voice.gender === genderFilter;
                return matchesSearch && matchesLanguage && matchesGender;
            });

            showVoicesGrid(filteredVoices);
        }

        // 设置功能
        function showSettings() {
            document.getElementById('settings-modal').classList.remove('hidden');
            document.getElementById('api-base-url').value = AppState.baseUrl;
            document.getElementById('api-token').value = AppState.token;
            document.getElementById('auto-play').checked = AppState.settings.autoPlay;
            document.getElementById('show-notifications').checked = AppState.settings.showNotifications;
        }

        function hideSettings() {
            document.getElementById('settings-modal').classList.add('hidden');
        }

        function saveSettings() {
            const baseUrl = document.getElementById('api-base-url').value;
            const token = document.getElementById('api-token').value;
            const autoPlay = document.getElementById('auto-play').checked;
            const showNotifications = document.getElementById('show-notifications').checked;

            AppState.baseUrl = baseUrl;
            AppState.token = token;
            AppState.settings = { autoPlay, showNotifications };
            
            // 保存到本地存储
            localStorage.setItem('auto-play', autoPlay);
            localStorage.setItem('show-notifications', showNotifications);

            hideSettings();
            showNotification('设置已保存', 'success');
            
            // 重新检查连接
            checkConnection();
        }

        // 工具函数
        function updateTextCount() {
            const text = document.getElementById('tts-text').value;
            const count = text.length;
            document.getElementById('text-count').textContent = `${count} / 5000 字符`;
        }

        function showLoading(elementId) {
            document.getElementById(elementId).classList.remove('hidden');
        }

        function hideLoading(elementId) {
            document.getElementById(elementId).classList.add('hidden');
        }

        function showElement(elementId) {
            document.getElementById(elementId).classList.remove('hidden');
        }

        function hideElement(elementId) {
            document.getElementById(elementId).classList.add('hidden');
        }

        function showNotification(message, type = 'info') {
            if (!AppState.settings.showNotifications) return;
            
            const container = document.getElementById('notification-container');
            const notification = document.createElement('div');
            
            const bgColor = {
                'success': 'bg-green-500',
                'error': 'bg-red-500',
                'warning': 'bg-yellow-500',
                'info': 'bg-blue-500'
            }[type] || 'bg-blue-500';

            notification.className = `${bgColor} text-white px-4 py-3 rounded-lg shadow-lg flex items-center space-x-2 fade-in`;
            notification.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'}"></i>
                <span>${message}</span>
            `;

            container.appendChild(notification);

            setTimeout(() => {
                notification.remove();
            }, 5000);
        }

        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).catch(err => {
                console.error('复制失败:', err);
            });
        }

        function formatDuration(seconds) {
            if (!seconds) return '0:00';
            const minutes = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);
            return `${minutes}:${secs.toString().padStart(2, '0')}`;
        }

        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        }

        function getStatusClass(status) {
            const classes = {
                'completed': 'bg-green-100 text-green-800',
                'processing': 'bg-yellow-100 text-yellow-800',
                'failed': 'bg-red-100 text-red-800',
                'pending': 'bg-gray-100 text-gray-800'
            };
            return classes[status] || 'bg-gray-100 text-gray-800';
        }

        function getStatusText(status) {
            const texts = {
                'completed': '已完成',
                'processing': '处理中',
                'failed': '失败',
                'pending': '等待中'
            };
            return texts[status] || status;
        }

        function updateVolume() {
            const volume = document.getElementById('volume-control').value;
            document.getElementById('volume-display').textContent = `${volume}%`;
            if (AppState.currentAudio) {
                AppState.currentAudio.volume = volume / 100;
            }
        }

        async function playPrevious() {
            showNotification('上一章功能开发中', 'info');
        }

        async function playNext() {
            showNotification('下一章功能开发中', 'info');
        }

        async function testVoice(voiceId) {
            showNotification('语音试听功能开发中', 'info');
        }

        // 启动应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>